package com.yricky.indesk.utils

import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import com.yricky.indesk.app
import com.yricky.indesk.model.pojo.AppEntrance

/**
 * @author Yricky
 * @date 2021/12/27
 */
val pkgMgr:PackageManager get() = app.packageManager

fun Context.callUninstall(entrance: AppEntrance){
    if(entrance.isEmpty() || !entrance.isValid())
        return
    startActivity(Intent(
        Intent.ACTION_DELETE,
        Uri.parse("package:${entrance.pkgName}")
    ))
}

fun getEntrance(pkgName:String):List<AppEntrance> =
    pkgMgr.getLaunchIntentForPackage(pkgName)
        ?.component?.let{
            listOf(AppEntrance(it.packageName,it.className))
        } ?: emptyList()

private val mainIntent:Intent by lazy{
    Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER)
}
fun getAllApps():List<AppEntrance> = pkgMgr.queryIntentActivities(mainIntent,0).flatMap {
    if(it.activityInfo.packageName != app.packageName)
        listOf(AppEntrance(it.activityInfo.packageName,it.activityInfo.name))
    else
        emptyList()
}